/**
 * LoginWebCrawler.java
 * Version: 1.0
 * Created in 06/08/2013
 * Created by Gerson Groth
 * 
 * Copyright
 */
package webcrawler.activities.webcrawler;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import webcrawler.activities.data.Data;

/**
 * The Class LoginWebCrawler.
 * 
 * @author Gerson Groth
 */
public class LoginWebCrawler {

	/** The logger. */
	private Logger logger = Logger.getLogger(LoginWebCrawler.class);

	/** The data. */
	private Data data;

	/**
	 * Instantiates a new login web crawler.
	 * 
	 * @param data
	 *            the data
	 */
	public LoginWebCrawler(Data data) {
		this.data = data;
	}

	/**
	 * Do login.
	 * 
	 * @param driver
	 *            the driver
	 */
	public void doLogin(final WebDriver driver) {
		logger.info("Abrindo página de login");

		driver.get("https://connect.garmin.com/signin");

		WebElement button = driver.findElement(By.id("login:signInButton"));

		// se usuário configurou username e password
		if (data.isLogin()) {

			WebElement login = driver.findElement(By
					.id("login:loginUsernameField"));
			WebElement pass = driver.findElement(By.id("login:password"));

			logger.info("Efetuando login com o usuário " + data.getUserName());

			login.sendKeys(data.getUserName());
			pass.sendKeys(data.getPassword());
			button.click();
		}

		WebDriverWait wait = new WebDriverWait(driver, 20);
		WebElement myDynamicElement = null;

		while (myDynamicElement == null) {
			try {

				myDynamicElement = wait
						.until(new ExpectedCondition<WebElement>() {
							public WebElement apply(WebDriver d) {
								if (d.getTitle().contains("Sign In"))
									return null;

								WebElement loggedIn = driver.findElement(By
										.className("nav-logged-in"));

								try {
									if (loggedIn == null) {
										return null;
									} else {
										return loggedIn;
									}
								} catch (NoSuchElementException ne) {
									return null;
								}

							}
						});
			} catch (Exception e) {
				logger.warn("Error waiting login: " + e.getMessage());
			}
		}

	}

}
